package com.strato.quartz.v1_0_0.annotation.handler;

import java.lang.annotation.Annotation;

import org.osgi.framework.Bundle;

import com.strato.annotation.base.v1_0_0.handler.AbstractAnnotationHandler;
import com.strato.annotation.base.v1_0_0.registry.ClassDescriptor;
import com.strato.annotation.osgi.v1_0_0.service.OsgiService;
import com.strato.base.env.v1_0_0.GlobalEnvironment;
import com.strato.quartz.v1_0_0.annotation.QuartzJob;
import com.strato.quartz.v1_0_0.schedule.Scheduler;
import com.strato.quartz.v1_0_0.schedule.SchedulerFactory;

@OsgiService
public class QuartzJobAnnotationHandler extends AbstractAnnotationHandler {

	@Override
	public void handleClass(Bundle bundle, Class<?> clazz, Annotation annotation) {
		if (!QuartzJob.class.equals(annotation.annotationType())) {
			return;
		}
		QuartzJob qj=clazz.getAnnotation(QuartzJob.class);
		String scheduler = qj.scheduler();
		String cron = qj.cron();
		String name=qj.name();
		GlobalEnvironment ge = GlobalEnvironment.getInstance();
		name=ge.resolveString(name);
		cron=ge.resolveString(cron);
		int version=qj.version();
		scheduler=ge.resolveString(scheduler);
//		Job job=(Job) ServiceCreator.newInstance(bundle, clazz);
		for(int i=0;i<10;i++){
			System.out.println("Trying to get scheduler instance");
			Scheduler s = SchedulerFactory.getInstance().getScheduler(scheduler);
			if(s==null){
				try {
					System.out.println("Wait for a second and retry");
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			if(s!=null){
				s.schedule(name,clazz, cron,version);
				break;
			}
		}
	}

	@Override
	public void handleUnresolveClass(Bundle bundle, ClassDescriptor classDescriptor) {
		Annotation anno = classDescriptor.getAnnotation(QuartzJob.class);
		if(anno==null){
			return;
		}
		QuartzJob qj=(QuartzJob) anno;
		String schedulerName = qj.scheduler();
		Scheduler scheduler = SchedulerFactory.getInstance().getScheduler(schedulerName);
		if(scheduler!=null){
			scheduler.unschedule(qj.name());
		}
	}

}
